package com.xy.core.annotation;

import cn.hutool.core.util.ClassUtil;
import com.xy.etl.kit.IEtlServer;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class RegisterDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    public final static String ALL_SERVER = "ALL";

    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }


    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        //配置目录
        String ymlKey = (String) metadata.getAnnotationAttributes(RegisterScan.class.getName()).get("ymlKey");
        if (ymlKey == null || ymlKey.trim().length() == 0) {
            return;
        }
        //取得配置启动的服务
        String configServer = environment.getProperty(ymlKey);
        if (configServer == null || configServer.length() == 0) {
            configServer = ALL_SERVER;
        }
        List<String> serverNames = Arrays.asList(configServer.split(","));
        //取得扫描基础目录，可以不配做
        String basePackage = (String) metadata.getAnnotationAttributes(RegisterScan.class.getName()).get("basePackage");
        if (basePackage != null && basePackage.trim().length() == 0) {
            basePackage = null;
        }
        //注册服务
        Set<Class<?>> serverSet = ClassUtil.scanPackageBySuper(basePackage, IEtlServer.class);
        RegisterServer registerEtlServer;
        for (Class<?> serverClass : serverSet) {
            registerEtlServer = serverClass.getAnnotation(RegisterServer.class);
            if (registerEtlServer == null) {
                continue;
            }
            if (!serverNames.contains(registerEtlServer.value()) && !serverNames.contains(ALL_SERVER)) {
                continue;
            }
            registry.registerBeanDefinition(registerEtlServer.value(), new RootBeanDefinition(serverClass));
        }
    }

}
